<?php

/**
 * This is the model class for table "{{order}}".
 *
 * The followings are the available columns in table '{{order}}':
 * @property string $order_id
 * @property string $order_code
 * @property string $user_id
 * @property string $order_status
 * @property string $order_total
 * @property string $order_fee
 * @property double $fee_delivery
 * @property string $order_zing_id
 * @property integer $product_count
 * @property string $primary_email
 * @property string $delivery_name
 * @property string $delivery_phone
 * @property string $delivery_company
 * @property string $delivery_address
 * @property string $delivery_city
 * @property integer $delivery_zone
 * @property string $delivery_postal_code
 * @property integer $delivery_country
 * @property integer $delivery_date
 * @property string $delivery_message
 * @property string $delivery_method_id
 * @property string $delivery_method_content
 * @property string $billing_name
 * @property string $billing_phone
 * @property string $billing_company
 * @property string $billing_address
 * @property string $billing_city
 * @property string $billing_zone
 * @property string $billing_postal_code
 * @property integer $billing_country
 * @property string $payment_method
 * @property string $data
 * @property integer $created
 * @property integer $modified
 * @property string $host
 * @property integer $workflow
 * @property string $store_currency
 * @property string $sale_currency
 */
class Order extends CActiveRecord {

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Order the static model class
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return '{{order}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.

        return array(
            array('order_code, order_status, order_total, order_fee, product_count, primary_email, payment_method, created, host', 'required'),
            array('product_count, created, workflow', 'numerical', 'integerOnly' => true),
            //array('fee_delivery, conversion_factor, conversion_multiplier', 'numerical'),
            //array('order_code, user_id, order_fee, delivery_method_id', 'length', 'max'=>20),
            array('order_status', 'length', 'max' => 32),
            array('order_total', 'length', 'max' => 16),
            array('order_zing_id, billing_phone', 'length', 'max' => 155),
            array('primary_email', 'length', 'max' => 96),
            array('delivery_name, delivery_phone, delivery_company, delivery_address, delivery_city, delivery_postal_code, billing_name, billing_company, billing_address, billing_city, billing_postal_code, host', 'length', 'max' => 255),
            array('billing_zone', 'length', 'max' => 50),
            array('payment_method', 'length', 'max' => 100),
            array('store_currency, sale_currency', 'length', 'max' => 3),
            array('delivery_message, data', 'safe'),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched. 
            array('order_id, order_code, user_id, order_status, order_total, order_fee, fee_delivery, order_zing_id, product_count, primary_email, delivery_name, delivery_phone, delivery_company, delivery_address, delivery_city, delivery_zone, delivery_postal_code, delivery_country, delivery_date, delivery_message, delivery_method_id, delivery_method_content, billing_name, billing_phone, billing_company, billing_address, billing_city, billing_postal_code, billing_country, payment_method, data, created, modified, host, workflow, store_currency, sale_currency', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'order_id' => 'Order',
            'order_code' => 'Order Code',
            'user_id' => 'User',
            'order_status' => 'Order Status',
            'order_total' => 'Order Total',
            'order_fee' => 'Order Fee',
            'fee_delivery' => 'Fee Delivery',
            'order_zing_id' => 'Order Zing',
            'product_count' => 'Product Count',
            'primary_email' => 'Primary Email',
            'delivery_name' => 'Delivery Name',
            'delivery_phone' => 'Delivery Phone',
            'delivery_company' => 'Delivery Company',
            'delivery_address' => 'Delivery Address',
            'delivery_city' => 'Delivery City',
            'delivery_zone' => 'Delivery Zone',
            'delivery_postal_code' => 'Delivery Postal Code',
            'delivery_country' => 'Delivery Country',
            'delivery_date' => 'Delivery Date',
            'delivery_message' => 'Delivery Message',
            'delivery_method_id' => 'Delivery Method',
            'delivery_method_content' => 'Delivery Method Content',
            'billing_name' => 'Billing Name',
            'billing_phone' => 'Billing Phone',
            'billing_company' => 'Billing Company',
            'billing_address' => 'Billing Address',
            'billing_city' => 'Billing City',
            'billing_zone' => 'Billing Zone',
            'billing_postal_code' => 'Billing Postal Code',
            'billing_country' => 'Billing Country',
            'payment_method' => 'Payment Method',
            'data' => 'Data',
            'created' => 'Created',
            'modified' => 'Modified',
            'host' => 'Host',
            'workflow' => 'Workflow',
            'store_currency' => 'Store Currency',
            'sale_currency' => 'Sale Currency',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search() {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('order_id', $this->order_id, true);
        $criteria->compare('order_code', $this->order_code, true);
        $criteria->compare('user_id', $this->user_id, true);
        $criteria->compare('order_status', $this->order_status, true);
        $criteria->compare('order_total', $this->order_total, true);
        $criteria->compare('order_fee', $this->order_fee, true);
        $criteria->compare('fee_delivery', $this->fee_delivery);
        $criteria->compare('order_zing_id', $this->order_zing_id, true);
        $criteria->compare('product_count', $this->product_count);
        $criteria->compare('primary_email', $this->primary_email, true);
        $criteria->compare('delivery_name', $this->delivery_name, true);
        $criteria->compare('delivery_phone', $this->delivery_phone, true);
        $criteria->compare('delivery_company', $this->delivery_company, true);
        $criteria->compare('delivery_address', $this->delivery_address, true);
        $criteria->compare('delivery_city', $this->delivery_city, true);
        $criteria->compare('delivery_zone', $this->delivery_zone);
        $criteria->compare('delivery_postal_code', $this->delivery_postal_code, true);
        $criteria->compare('delivery_country', $this->delivery_country);
        $criteria->compare('delivery_date', $this->delivery_date);
        $criteria->compare('delivery_message', $this->delivery_message, true);
        $criteria->compare('delivery_method_id', $this->delivery_method_id, true);
        $criteria->compare('delivery_method_content', $this->delivery_method_content, true);
        $criteria->compare('billing_name', $this->billing_name, true);
        $criteria->compare('billing_phone', $this->billing_phone, true);
        $criteria->compare('billing_company', $this->billing_company, true);
        $criteria->compare('billing_address', $this->billing_address, true);
        $criteria->compare('billing_city', $this->billing_city, true);
        $criteria->compare('billing_zone', $this->billing_zone, true);
        $criteria->compare('billing_postal_code', $this->billing_postal_code, true);
        $criteria->compare('billing_country', $this->billing_country);
        $criteria->compare('payment_method', $this->payment_method, true);
        $criteria->compare('data', $this->data, true);
        $criteria->compare('created', $this->created);
        $criteria->compare('modified', $this->modified);
        $criteria->compare('host', $this->host, true);
        $criteria->compare('workflow', $this->workflow);
        $criteria->compare('store_currency', $this->store_currency, true);
        $criteria->compare('sale_currency', $this->sale_currency, true);

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }

    public static function processCheckout($modelFrm) {
        $uid = Yii::app()->user->id;
        $addres = UserAddress::model()->findByAttributes(array('uid' => $uid, 'status' => 1));
        $user = User::model()->findByPk($uid);
        $currency = $modelFrm['payment_currency'];
        $method = $modelFrm['payment_method'];

        $listVND = array("vtc_payment", "oncome_nd");
        $listAUD = array("paypal");
        $listUSD = array("oncome", "paypal");
        $fee = 0;
        if (in_array(strtolower($method), $listVND)) {
            $fee = 2000;
        } else if (in_array(strtolower($method), $listAUD)) {
            $fee = 0.29;
        } else if (in_array(strtolower($method), $listUSD)) {
            $fee = 0.29;
        }
        $storeCurr = Yii::app()->user->getState('currency');
        $saleCurr = $currency;
        $totalAmount = Yii::app()->shoppingCart->getCost();
        if ($saleCurr != $storeCurr) {
            $totalAmount = Currency::convert($storeCurr, $saleCurr, $totalAmount);
        }

        $model = new Order();

        $model->order_code = "khothe_" . time();
        $model->user_id = $uid;
        $model->order_status = "in_checkout";
        $model->order_total = $totalAmount;
        $model->order_fee = $fee;
        //$model->order_zing_id= ($modelFrm->zingId !='') ? $modelFrm->zingId : '';

        $model->product_count = Yii::app()->shoppingCart->getItemsCount();
        $model->primary_email = $user->email;
        //billing address
        $model->billing_name = ($user->display_name != '') ? $user->display_name : $user->username;

        $model->billing_phone = $addres->phone;
        $model->billing_company = $addres->company;
        $model->billing_address = $addres->street;
        $model->billing_city = $addres->city;
        $model->billing_zone = $addres->region;
        $model->billing_postal_code = $addres->zipCode;
        $model->billing_country = $addres->countryCode;

        //khong hieu sao thanh toan qua tang khong luu dc order
        //delivery infomation
        /*
          if(intval($modelFrm['delivery_method']) != 0){
          $delivery_id = intval($modelFrm['delivery_method']);
          $delivery = DeliveryMethod::model()->findByPk($delivery_id);
          if($delivery->currency != $saleCurr) $delivery_fee = Currency::convert($delivery_cur, $saleCurr, intval($delivery->fee));
          else $delivery_fee = $delivery->fee;

          $model->delivery_name        = $modelFrm['delivery_name'];
          $model->delivery_company     = $modelFrm['delivery_company'];
          $model->delivery_phone       = $modelFrm['delivery_phone'];
          //$model->delivery_company   = $modelFrm['delivery_email'];
          $model->delivery_address     = $modelFrm['delivery_address'];
          $model->delivery_city        = $modelFrm['delivery_city'];
          $model->delivery_date        = ($modelFrm['delivery_date']!= '')? strtotime($modelFrm['delivery_date']) : '';
          $model->delivery_message     = $modelFrm['delivery_message'];
          $model->delivery_method_id   = $modelFrm['delivery_method'];
          $model->delivery_postal_code = '70000';
          $model->delivery_country     = 704;
          $model->fee_delivery         = $delivery_fee;
          }
         */
        $model->payment_method = $method;
        $model->created = time();
        $model->host = ip();
        $model->workflow = 1;
        $model->store_currency = Yii::app()->user->getState('currency');
        $model->sale_currency = $currency;
        $model->save();


        $positions = Yii::app()->shoppingCart->getPositions();
        foreach ($positions as $pos) {
            $pid = $pos->id;
            $qty = $pos->getQuantity();
            $price = $pos->getPrice();
            $priceS = $pos->getSumPrice();
            if ($saleCurr != $storeCurr) {
                $price = Currency::convert($storeCurr, $saleCurr, $price);
                $priceS = Currency::convert($storeCurr, $saleCurr, $priceS);
            }
            $objOrder = new ObjectOrder();
            $objOrder->object_id = $pid;
            $objOrder->order_id = $model->order_id;
            $objOrder->order_number = $qty;
            $objOrder->object_order_price = $price;
            $objOrder->object_order_total_price = $priceS;
            $objOrder->save();
            unset($objOrder);
        }
        return $model;
        unset($model);
    }

}
